<?php

namespace Portal\InvoiceBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;


use Portal\UserBundle\Controller\LoginController;
use Portal\InvoiceBundle\Entity\BankAttempt;

class InvoiceController extends Controller
{
    public function showAction($id, $notificationId = null)
    {
      
        $user = LoginController::checkUser($this->container->get('security.context'));
        
        $invoice = $this->getDoctrine()->getEntityManager()->getRepository('PortalInvoiceBundle:Invoice')->findInvoiceById((int) $id, (int) $user->getId());
        if(!$invoice){
          $this->get('session')->setFlash('error', 'Энэ нэхэмжлэх байхгүй байна.');
          return $this->redirect($this->generateUrl('homepage'));
        }
        
        $this->showNotification($notificationId);
        $bankArray = $this->getDoctrine()->getEntityManager()->getRepository('PortalInvoiceBundle:Bank')->findAllActiveBanks();
        
        return $this->render('PortalInvoiceBundle:Invoice:show.html.twig', array(
            'invoiceId' => $id,
            'bankArray' => $bankArray,
            'amount' => $invoice['AMOUNT']
            ));
    }
    
    public function goToBankAction(Request $request)
    {
      $requestParams = $request->request;
      $user = LoginController::checkUser($this->container->get('security.context'));
      // GET PARAMS
      $invoiceId = $requestParams->get('invoiceId');
      $amount = $requestParams->get('amount');
      $bank = $requestParams->get('bank');      
      if($bank && $invoiceId && $amount)
      { 
        // FIND BANK
        $bankObject = $this->getDoctrine()->getEntityManager()->getRepository('PortalInvoiceBundle:Bank')->find((int) $bank);
        if(!$bankObject)
        {
          $this->get('session')->setFlash('error', 'Уучлаарай банк сонгоно уу.');
          return new RedirectResponse($request->headers->get('referer'));
        }
        
        // 
        
        $attemptParams = $this->getDoctrine()->getEntityManager()->getRepository('PortalInvoiceBundle:Invoice')->findInvoiceById((int) $invoiceId, (int) $user->getId());
        
        if($attemptParams['AMOUNT'] != $amount)
        {
          $this->get('session')->setFlash('error', 'Дүн буруу байна.');
          return new RedirectResponse($request->headers->get('referer'));
        }
        
        if(!$attemptParams)
        {
          $this->get('session')->setFlash('error', 'Уучлаарай мэдээлэл дутуу байна.');
          return new RedirectResponse($request->headers->get('referer'));
        }
        
        $invoice = $this->getDoctrine()->getEntityManager()->getRepository('PortalInvoiceBundle:Invoice')->find((int) $invoiceId);
        $tutor = $this->getDoctrine()->getEntityManager()->getRepository('PortalInvoiceBundle:Tutor')->find($attemptParams['TUTOR_ID']);
        $userObject = $this->getDoctrine()->getEntityManager()->getRepository('PortalInvoiceBundle:User')->find((int) $user->getId());
        $bankObject = $this->getDoctrine()->getEntityManager()->getRepository('PortalInvoiceBundle:Bank')->find((int) $bank);
        
        $bankAttempt = new BankAttempt();
        $bankAttempt->setUser($userObject);
        $bankAttempt->setTutor($tutor);
        $bankAttempt->setBank($bankObject);
        $bankAttempt->setInvoice($invoice);
        $bankAttempt->setToUrl($bankObject->getUrl());
        $bankAttempt->setInvoiceId($invoiceId);
        $bankAttempt->setAmount($attemptParams['AMOUNT']);
        $bankAttempt->setStatus($this->container->getParameter('statusBankAttemptCall'));
        $bankAttempt->setCreatedAt(new \DateTime());
        $bankAttempt->setCreatedIp($_SERVER['REMOTE_ADDR']);
        // SAVE CONTRACT
        $em = $this->getDoctrine()->getManager();
        $em->persist($bankAttempt);
        $em->flush();
        
        if($bankAttempt->getId())
        {
          
          header("Location: http://www.tdbm.mn");
          die;
          
        }
        
        
      }else{
        $this->get('session')->setFlash('error', 'Уучлаарай банк, төлбөрийн хэмжээгээ зөв сонгоно уу.');
        return new RedirectResponse($request->headers->get('referer'));
      }
      
    }


    private function showNotification($notificationId)
    {
      $notification = $this->getDoctrine()->getEntityManager()->getRepository('PortalNotificationBundle:Notification')->find((int) $notificationId);
      if ($notification) {

        $user = LoginController::checkUser($this->container->get('security.context'));
        
        if (in_array($this->container->getParameter('ROLE_USER'), $user->getRoles())) {
          $notification->setStatus($this->container->getParameter('notificationStatusRead'));
        } else if (in_array($this->container->getParameter('ROLE_TUTOR'), $user->getRoles())) {
          $notification->setStatusTutor($this->container->getParameter('notificationStatusRead'));
        }
        // SAVE CONTRACT
        $em = $this->getDoctrine()->getManager();
        $em->persist($notification);
        $em->flush();

        return true;
      }
    }
}
